package com.chookss.home.knowledge;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.entity.UploadEntity;
import com.chookss.home.knowledge.adaper.UploadAdapter;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class UploadListActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.smrRf)
    SmartRefreshLayout smrRf;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.tvEmpty)
    TextView tvEmpty;

    private UploadAdapter adapter;
    private List<UploadEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private String tag = "UploadListActivity_DownloadFile";//下载文件打的标签

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_document);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        commonTitleTxt.setText("最新上传");
        tvEmpty.setText("暂无上传数据");
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new UploadAdapter(R.layout.item_upload, this, list, 1, tag);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setAdapter(adapter);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        smrRf.autoRefresh();
        registerBoradcastReceiver();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<UploadEntity>>>() {
        }.getType(), null, Urls.getMyUpload, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<UploadEntity>>() {
            @Override
            public void onSuccess(List<UploadEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null || llNone == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
                    int old = list.size();
                    if(getResources().getString(R.string.app_knowledge_name).equals(new ShareUtils().getString(UploadListActivity.this, StaticClass.COMPANYNAME,""))){
                       //应付华为市场所以不显示视频
                        List<UploadEntity> data2=new ArrayList<>();
                        data2.addAll(data);
                        for (int i = 0; i <data2.size() ; i++) {
                            if(data2.get(i).getResourceType().equals("2")||data2.get(i).getResourceType().equals("3")){
                                data2.remove(i);
                                if (i < data2.size()) {
                                    i--;
                                }
                            }
                        }

                        list.addAll(data2);
                        adapter.notifyItemRangeChanged(old, data2.size());
                    }else{
                        list.addAll(data);
                        adapter.notifyItemRangeChanged(old, data.size());
                    }
                    smrRf.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            HashMap<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("DocumentPreview_error")) {
                for (int i = 0; i < list.size(); i++) {
                    if ("1".equals(list.get(i).getResourceType())) {
                        if (list.get(i).getDataBase().getDataCode().equals(map.get("DocumentPreview_error"))) {
                            list.get(i).getDataBase().setError(true);
                        }
                    }

                }
            }

        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }


    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                for (int i = 0; i < list.size(); i++) {
                    if ("1".equals(list.get(i).getResourceType())) {
                        if (list.get(i).getDataBase().getDataCode().equals(recevierDataCode)) {
                            if (!list.get(i).getDataBase().isOpen()) {
                                if(encryptStatus){
                                    list.get(i).getDataBase().setOpen(true);
                                }
                                dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                            }

                        }
                    }

                }

            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                startActivity(newIntent);

            }
        } else {
            if (percent > 0 && percent < 100) {
                if (adapter != null) {
                    list.get(position).getDataBase().setProgress(percent);
                    adapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (adapter != null) {
                    list.get(position).getDataBase().setProgress(100);
                    adapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(UploadListActivity.this, fileUrl, fileName, recevierDataCode, tag);
                        }
                    }.start();
                }


            }else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(tag);// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
    }

    @OnClick(R.id.common_title_back)
    public void onClick() {
        finish();
    }
}
